package autoTest.request;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import autoTest.command.ErrorCode;
import autoTest.command.Params;
import autoTest.device.DeviceInfo;
import autoTest.device.Platform;
import autoTest.device.Status;
import autoTest.utils.TextUtils;
import main.ServerMain;
import net.sf.json.JSONObject;

public class ReportStatusPart extends RequestPart {
	private static final long serialVersionUID = 2271797150647771300L;
	public ReportStatusPart() {}
    
    @Override public void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	String platformStr = req.getParameter(Params.PLAT_FORM);
    	String deviceIdStr = req.getParameter(Params.DEVICE_ID);
    	String statusStr = req.getParameter(Params.STATUS);
    	
    	
    	System.out.println("[ReportStatusPart] platformStr:" + platformStr + ",deviceIdStr:" + deviceIdStr + ",statusStr:" + statusStr);
    	if (TextUtils.isEmpty(platformStr) || TextUtils.isEmpty(deviceIdStr) || TextUtils.isEmpty(statusStr)) {
    		doResponse(resp, ErrorCode.ERR_PARAM_ERROR);
    	} else {
    		DeviceInfo get = ServerMain.allDeviceInfo.get(deviceIdStr);
    		if (get == null) {
    			get = new DeviceInfo(deviceIdStr);
    		}
    		if (Platform.valueStrOf(platformStr) == null) {
    			doResponse(resp, ErrorCode.ERR_PARAM_ERROR);
    			return;
    		}
    		Status status = null;
    		try {
    			status = Status.valueStrOf(statusStr);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		if (status == null) {
    			doResponse(resp, ErrorCode.ERR_PARAM_ERROR);
    		}
    		get.setPlatform(Platform.valueStrOf(platformStr));
    		get.setStatus(status);
    		ServerMain.allDeviceInfo.put(deviceIdStr, get);
    		doResponse(resp, ErrorCode.SUCCESS);
    	}
    }
    
	protected void doResponse(HttpServletResponse resp, int code) throws ServletException, IOException {
		System.out.print("post request");
		resp.setCharacterEncoding("UTF-8");  
		resp.setContentType("text/plain");
		resp.setStatus(HttpServletResponse.SC_OK);
		PrintWriter pWriter = resp.getWriter();
		JSONObject joRet = new JSONObject();
		joRet.put(Params.CODE, code);
		pWriter.println(joRet.toString());  
	}
}
